const puppeteer = require('puppeteer')
const { parentPort,workerData } = require('worker_threads')

async function start_grab(browser,stock_data){
    try{
        for(i in stock_data){
            first = true;
            const page = await browser.newPage()
            page.on('response', async response => {
                try{
                    if(response.request().resourceType()==="xhr"
                        && response.status() === 200 
                        && response.url().includes('getstockquotation') ){
                            parentPort.postMessage(await response.json())
                    }
                    // if(response.request().url().includes('sug?')){
                    //     console.log(response.request().url())
                    //     if(response.request().resourceType()==="xhr")
                    //         console.log(await response.json())
                    // }
                }catch(e){
                    console.log(e)
                }
            })

            //getrelatedblock?stock=  板块
            await page.goto('https://gushitong.baidu.com')
            await page.type("#search",stock_data[i],{delay:50})
            const element = await page.waitForSelector('.list-item-wrap')
            const item = await element.waitForSelector('.list-item')
            await item.click()
            console.log('====='+stock_data[i])
        }
    }catch(e){
        console.log(e)
    }
}

async function run(){
    const browser = await puppeteer.launch({
        headless: false,
        //ignoreHTTPSErrors: true,
        //devtools:true
    })
    parentPort.on('message', o => start_grab(browser, o))
    parentPort.on('error', o => console.log('stock',o))
    parentPort.on('exit',async () => await browser.close())
    start_grab(browser, ['中国银行'])
}
run()
